<?php

/**
 * Created by PhpStorm.
 * User: yuanluke
 * Date: 4/25/16
 * Time: 10:22
 */

namespace App\Http\Utils\Common;

use App\Http\Model\WxFormIdData;
use Carbon\Carbon;
use DB;
use GuzzleHttp\Client;
use Log;

class WechatUtils
{

    public static function getToken()
    {
        $tokenUrl = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . Consts::WX_APPID . '&secret=' . Consts::WX_SECRET;
        $client = new Client();

        $response = $client->request('GET', $tokenUrl);
        $json = \GuzzleHttp\json_decode($response->getBody());
        $token = empty($json->access_token) ? null : $json->access_token;
        Log::info('token='.$token);
        return $token;
    }

    //设置模板参数
    public function set_complate_params($complate_id, $token, $form_id, $openid,array $params,$page)
    {
        $template_data = [];
//        foreach ($params as $k => $item){
//            $tmp = [];
//            $tmp['keyword'.($k+1)] = $item;
//            array_merge($template_data,$tmp);
//        }
        if (!empty($openid)) {
            $postData = [
                "touser" => $openid,
                "template_id" => $complate_id,
                "page" => $page,//TODO  page
                "form_id" => $form_id, //TODO form_id
                "data" => $params,
//                            "emphasis_keyword"=> "keyword1.DATA"
            ];
            return $this->send($token, $postData);
        }
    }

    public function send($token, $postData)
    {
        $url = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=' . $token;
        $client = new Client();
        $response = $client->request('POST', $url, [
            'json' => $postData
        ]);
        $json = \GuzzleHttp\json_decode($response->getBody());
        if ($json->errcode == 0) {
            Log::info('发送模板成功' . $json->errmsg);
            return ture;
        } else {
            Log::info('发送模板失败' . $json->errmsg);
            return false;
        }
    }


    public function sendTemplate($complate_id, $own_id, $account_type, array $openids,array $params,$page)
    {
        $wx_form_id_data = WxFormIdData::where(['account_type' => $account_type, 'own_id' => $own_id])
            ->where('over_date', '>', Carbon::now())->orderBy('over_date', 'desc')->first();
        if ($wx_form_id_data == null) {
            Log::debug('找不到对应的form_id');
            return false;
        } else {
            //1,查询有效的form_id
            $form_id = $wx_form_id_data->formid;
//            $form_id = '8ce0b3f7a7a45b8500575d6f6deea37c';
            //2,获取token
//            $token = 'uQDmbQR1doi65FEKz5SzM9slL-IgOMaOMc9VVojcdDaCLvASpzA5KhDryeOzXFNYp-KgMGGsQcBvJOc2hlxzY8oDa7xiehl4ar5mGoYpQcemDmE0QgGENnYtL4nXX4u5XTRfAGARNL';
            $token = $this->getToken();
            if (empty($token)) {
                Log::debug('token获取失败');
                return false;
            }
            foreach ($openids as $openid) {
                //设置模板参数并发送
                $this->set_complate_params($complate_id, $token, $form_id, $openid,$params,$page);
            }
        }
        return true;

    }

}